/*
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
 * 
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common Development
 * and Distribution License("CDDL") (collectively, the "License").  You
 * may not use this file except in compliance with the License. You can obtain
 * a copy of the License at https://jersey.dev.java.net/CDDL+GPL.html
 * or jersey/legal/LICENSE.txt.  See the License for the specific
 * language governing permissions and limitations under the License.
 * 
 * When distributing the software, include this License Header Notice in each
 * file and include the License file at jersey/legal/LICENSE.txt.
 * Sun designates this particular file as subject to the "Classpath" exception
 * as provided by Sun in the GPL Version 2 section of the License file that
 * accompanied this code.  If applicable, add the following below the License
 * Header, with the fields enclosed by brackets [] replaced by your own
 * identifying information: "Portions Copyrighted [year]
 * [name of copyright owner]"
 * 
 * Contributor(s):
 * 
 * If you wish your version of this file to be governed by only the CDDL or
 * only the GPL Version 2, indicate your decision by adding "[Contributor]
 * elects to include this software in this distribution under the [CDDL or GPL
 * Version 2] license."  If you don't indicate a single choice of license, a
 * recipient has the option to distribute your version of this file under
 * either the CDDL, the GPL Version 2 or to extend the choice of license to
 * its licensees as provided above.  However, if you add GPL Version 2 code
 * and therefore, elected the GPL Version 2 license, then the option applies
 * only if the new code is made subject to such option by the copyright
 * holder.
 */
/*
 * The contents of this file are subject to the terms
 * of the Common Development and Distribution License
 * (the "License").  You may not use this file except
 * in compliance with the License.
 *
 * You can obtain a copy of the license at
 * http://www.opensource.org/licenses/cddl1.php
 * See the License for the specific language governing
 * permissions and limitations under the License.
 */

/*
 * FormReader.java
 *
 * Created on November 21, 2007, 12:43 PM
 *
 */

package com.tianji.jersey.resource;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author mh124079
 */
@Consumes("multipart/form-data")
@Provider
public class FormReader implements MessageBodyReader<String> {
	@Context
	HttpServletRequest servletRequest;
	
    public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    	System.out.println("=================isReadable========="+type.equals(String.class));
        return type.equals(String.class);
    }
    @Override
    public String readFrom(Class<String> type, Type genericType,
            Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> headers, 
            InputStream in) throws IOException {
    	StringBuilder sb = new StringBuilder();
    	System.out.println("=====type=============>" + type);
    	System.out.println("=====genericType=============>" + genericType);
    	System.out.println("=====annotations=============>" + annotations);
    	System.out.println("=====mediaType=============>" + type);
    	System.out.println("=====headers=============>" + headers);
//    	System.out.println("=====InputStream=============>" + readAsString(in));
		boolean isMultipart = ServletFileUpload.isMultipartContent(servletRequest);
		System.out.println("=====isMultipart=============>" + isMultipart);
		
		// Create a factory for disk-based file items
		FileItemFactory factory = new DiskFileItemFactory();

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);

		// Parse the request
		List<FileItem> items = null;
		try {
			items = upload.parseRequest(servletRequest);
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		for(FileItem item : items){
			if(item.isFormField()){
				sb.append("filed name :"+item.getFieldName());
				sb.append(" name :"+item.getString());
			}else{
				sb.append("filename--->"+item.getName()+"\n");
				sb.append("fileSize--->"+item.getSize()+"\n");
				sb.append("OriginalFilename--->"+item.getName()+"\n");
				sb.append("content type--->"+item.getContentType()+"\n");
			}
			
		}
		/**
		 * old pattern
		FileItemIterator iter = upload.getItemIterator(servletRequest);
		System.out.println("=====iter=============>" + iter.hasNext());

		System.out.println("=====iter=============>" + iter.hasNext());
		while (iter.hasNext()) {
		    FileItemStream item = iter.next();
		    String name = item.getFieldName();
		    InputStream stream = item.openStream();
		    if (item.isFormField()) {
		        System.out.println("Form field " + name + " with value "
		            + Streams.asString(stream) + " detected.");

		        System.out.println(item);
		    } else {
				sb.append("filename--->"+item.getName()+"\n");
				sb.append("fileSize--->"+Streams.asString(stream).length()+"\n");
//				sb.append("OriginalFilename--->"+map.getOriginalFilename()+"\n");
				sb.append("content type--->"+item.getContentType()+"\n");

		        System.out.println("File field " + name + " with file name "
		            + item.getName() + " detected.");
		        // Process the input stream
		    }
		}
		//ServletContainerRequest r = (ServletContainerRequest)request;
		 * 
		 */
       
        return sb.toString();
    }
    public final String readAsString(InputStream in) throws IOException {
        Reader reader = new InputStreamReader(in);
        StringBuilder sb = new StringBuilder();
        char[] c = new char[1024];
        int l;
        while ((l = reader.read(c)) != -1) {
            sb.append(c, 0, l);
        } 
        return sb.toString();
    }

}
